package com.myutils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import androidx.appcompat.app.AppCompatActivity;

import com.nativec.tools.ModuleManager;

/**
 * 类描述：home键 和 recent_apps键 监听 <br/>
 * 创建人：lwj<br/>
 * 创建时间：2019/8/13 13:10 <br/>
 */
public class HomeAndRecentAppsKeyReceiver {
    private boolean mSwitchFlag = false;
    private VirtualKeyListenerBroadcastReceiver mReceiver;

    private HomeAndRecentAppsKeyReceiver() {
    }

    public static HomeAndRecentAppsKeyReceiver newInstance() {
        return new HomeAndRecentAppsKeyReceiver();
    }

    public boolean isSwitchFlag() {
        return mSwitchFlag;
    }

    public void setSwitchFlag(boolean switchFlag) {
        mSwitchFlag = switchFlag;
    }

    public void onStart(AppCompatActivity activity) {
        if (activity == null) {
            return;
        }
        //1.接出第一步 添加 home键 和 recent_apps键 监听
        if (mReceiver == null) {
            mReceiver = new VirtualKeyListenerBroadcastReceiver();
            IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
            activity.registerReceiver(mReceiver, intentFilter);
        }
        if (mSwitchFlag) {
            ModuleManager.newInstance().setUHFStatus(true);
        }
    }

    public void unregisterReceiver(AppCompatActivity activity) {
        if (activity == null || mReceiver == null) {
            return;
        }
        activity.unregisterReceiver(mReceiver);
    }

    /**
     * 接出第一步
     */
    private class VirtualKeyListenerBroadcastReceiver extends BroadcastReceiver {
        private final String SYSTEM_REASON = "reason";
        private final String SYSTEM_HOME_KEY = "homekey";
        private final String SYSTEM_RECENT_APPS = "recentapps";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String systemReason = intent.getStringExtra(SYSTEM_REASON);
                if (systemReason != null) {
                    if (systemReason.equals(SYSTEM_HOME_KEY)) {
                        System.out.println("Press HOME key");
                    } else if (systemReason.equals(SYSTEM_RECENT_APPS)) {
                        System.out.println("Press RECENT_APPS key");
                        ModuleManager.newInstance().setUHFStatus(false);
                        mSwitchFlag = true;
                    }
                }
            }
        }

    }
}
